package com.example.question.list.list2;

import com.example.question.list.list1.List;
import com.example.question.list.list1.ListNode;

/**
 * @Date 2023-07-08
 * @Author Jonathan
 */
public class Code08_23 {
    public static void main(String[] args) {
        ListNode l1 = List.createList(new int[]{1, 4, 7});
        ListNode l2 = List.createList(new int[]{2, 5, 8});
        ListNode l3 = List.createList(new int[]{3, 6, 9});
        ListNode[] listNodes = new ListNode[]{l3, l2, l1};
        Code08_23 code = new Code08_23();
        code.mergeKLists(listNodes);
    }


    public ListNode mergeKLists(ListNode[] lists) {
        ListNode dummyHead = new ListNode(-1);
        ListNode retCur = dummyHead;
        ListNode[] heads = lists;
        int index = 0;
        while (true) {
            int val = Integer.MAX_VALUE;
            for (int i = 0; i < heads.length; i++) {
                if (heads[i] != null && heads[i].val < val) {
                    val = heads[i].val;
                    index = i;
                }
            }
            if (val == Integer.MAX_VALUE) {
                break;
            }
            heads[index] = heads[index].next;
            retCur.next = new ListNode(val);
            retCur = retCur.next;
        }
        return dummyHead.next;
    }
}
